const {exec, escape} = require('../db/mysql');
const {SuccessModel, ErrorModel} = require('../model/resModel');
const captchapng = require('captchapng2');

/**
 * 检查用户名是否存在
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 */
const checkUsername = async (ctx, next) => {
    let {username} = ctx.request.body;
    username = escape(username);
    // 查询数据库中是否存在该用户名
    const sql = `select username from users where username=${username};`;
    const users = await exec(sql);
    if (users.length !== 0) {
        ctx.body = new ErrorModel('用户名已经存在', '002');
        return;
    }
    ctx.body = new SuccessModel('可以注册', '001');
};

/**
 * 注册
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 */
const doRegister = async (ctx, next) => {
    let {username, password, email, vCode} = ctx.request.body;
    const registerTime = Date.now();
    // 优先判断验证码
    if (vCode !== ctx.session.vCode) {
        return ctx.body = new ErrorModel({}, '验证码不正确', '003');
    }
    username = escape(username);
    password = escape(password);
    email = escape(email);
    const sql = `select * from users where username=${username} and email=${email}`;
    const users = await exec(sql);
    let user;
    if (users.length !== 0) {
        if (users.length > 0) return ctx.body = new ErrorModel('用户名和邮箱都存在', '004');
        user = users[0];
        if (user.username === username && user.email === email) return ctx.body = new ErrorModel('用户名和邮箱都存在', '004');
        if (user.username === username) return ctx.body = new ErrorModel('用户名已经存在', '002');
        if (user.email === email) return ctx.body = new ErrorModel('邮箱已经存在', '002');
    }
    // 插入数据
    const insertSql = `insert into users(username,password,email,register_time) values (${username}, ${password}, ${email}, '${registerTime}');`;
    const result = await exec(insertSql);
    if (result.affectedRows === 1) {
        return ctx.body = new SuccessModel(result, '注册用户成功', '001');
    }
};

/**
 * 登录
 * @param ctx
 * @param next
 * @returns {Promise<ErrorModel>}
 */
const doLogin = async (ctx, next) => {
    let {username, password} = ctx.request.body;
    username = escape(username);
    password = escape(password);
    const sql = `select * from users where username=${username} and password=${password}`;
    const users = await exec(sql);
    const user = users[0];
    password = password.replace(/\'/g, '');
    if (users.length === 0 || user.password !== password) {
        return ctx.body = new ErrorModel(user, '用户名或者密码不正确', '002');
    }
    // 用户存在且密码一致，登录操作
    ctx.session.user = user;
    ctx.body = new SuccessModel(user, '登录成功', '001');
};

/**
 * 生成验证码
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 */
const getPic = async (ctx, next) => {
    const number = Math.round(Math.random() * 9000 + 1000);
    const png = new captchapng(80, 30, number);
    // 保存结果到用户的session中，响应cookie
    ctx.session.vCode = number + '';
    ctx.response.set('Content-Type', 'image/png');
    ctx.body = png.getBuffer();
};

/**
 * 退出
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 */
const logout = async (ctx, next) => {
    // 清除登录信息,就是退出
    ctx.session.user = null;
    // 页面重定向
    ctx.response.redirect('/user/login');
};

module.exports = {checkUsername, doRegister, doLogin, getPic, logout};